const { DEFAULT_ENCODING } = require('crypto');
const { Remarks } = require('../models/remarks');


//获取评论列表（对列表进行分类）
async function handleRemarkPagenition(req) {
    console.log("req", req.body);
    const { pageSize, pageNumber, conditions = { type: "", id: '' } } = req.body;
    let data;
    let totalCount;
    //remarkType 代表评价的类别,carId代表车辆id
    const remarkType = conditions.type;
    const carId = conditions.id;

    //如果type=""和id=“”
    if (remarkType == "" && carId == "") {
        totalCount = await Remarks.countDocuments();
    }

    //如果type不为空，id为空
    if (remarkType != "" && carId == "") {
        const arr = await Remarks.find({ rateStatus: remarkType });
        totalCount = arr.length;
    }

    const num = (pageNumber - 1) * pageSize;//上一页的数据总数
    if (totalCount <= num) {
        return [];//表示当前没有数据
    }

    //获取数据  如果车辆id不存在
    if (carId == "") {
        data = await Remarks.find({
            ["rateStatus"]: {
                $regex: remarkType,
                $options: '$i',//模糊匹配只能是字符串
            },
        }).populate("carId").populate("userId").populate("orderId")
            .limit(pageSize).skip((pageNumber - 1) * pageSize)
    }

    // console.log('data', data);
    // console.log("total", totalCount);
    // console.log('data长度', data.length);

    return {
        data: data,
        totalCount
    }


}

//获取评论列表
async function getRemarkList(req, res, next) {
    try {
        const data = await handleRemarkPagenition(req);
        console.log("body", req.body);
        res.send({ code: 1, data: { ...data, ...req.body } });
    } catch (error) {
        console.log("err", error);
        next(error);
    }
}

//获取各类评论的数量
async function getAllRemarkCount(req, res, next) {
    try {
        // count: { $sum: 1 }类似于计算数字，_id必须， $match//条件筛选关键词，$group：{}内的是分组条件
        // {$sort://排序关键词 {count:-1//排序规则}}]);
        //aggregate: 统计和计数
        const msg = await Remarks.aggregate([
            { $match: { "rateStatus": { $in: ["好评", "中评", "差评"] } } },
            { $group: { _id: { kind: "$rateStatus" }, count: { $sum: 1 } } },
        ]);
        let data = {};
        msg.forEach(item => {
            const key = item._id.kind;
            data[key] = item.count
        })
        console.log(data);
        res.send({
            code: 1,
            data
        })
    } catch (error) {
        console.log("err", error);
        next(error);
    }
}
module.exports = {
    getRemarkList,
    getAllRemarkCount

};